package org.testframe;

import java.util.ArrayList;
import java.util.List;

/**
 * 流程构建器
 * @author 丁常磊
 * @date 2023/11/17 9:47
 */

public class FlowBuilder {

    private final List<ActionBuilder> actions = new ArrayList<>();

    private ActionBuilder finallyAction;

    private ActionBuilder errorAction;

    public FlowBuilder errorAction(ActionBuilder errorAction) {
        this.errorAction = errorAction;
        return this;
    }

    public FlowBuilder finallyAction(ActionBuilder finallyAction) {
        this.finallyAction = finallyAction;
        return this;
    }

    private FlowContext flowContext;

    public FlowBuilder flowContext(FlowContext flowContext) {
        this.flowContext = flowContext;
        return this;
    }

    /**
     * 下一步的流程
     * @param action
     * @return
     */
    public FlowBuilder then(ActionBuilder action) {
        actions.add(action);
        return this;
    }

    /**
     * 构建流程
     * @return
     */
    public Flow build() {
        FlowContext c = flowContext;
        if (c == null) {
            c = new FlowContext();
        }

        List<Action> acs = new ArrayList<>();
        for (ActionBuilder action : actions) {
            acs.add(action.create());
        }

        Action fa = null;
        if (finallyAction != null) {
            fa = finallyAction.create();
        }

        Action ea = null;
        if (errorAction != null) {
            ea = errorAction.create();
        }
        return new Flow(acs,fa,ea, c);
    }

}
